<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * bookhistory_model
 * Build by Phuc Nguyen
 * Contact : nguyenvanphuc0626@gmail.com
 */

class Bookhistory_model extends MY_Model{
	
	public function __construct(){
		parent::__construct();
		$this->table_name = 'book_history';
	}
        
        public function bookingOk($params){
            $this->db->select('sum(segments) AS sum, count(*) AS count');
            $this->db->from($this->table_name);
            $this->db->where('owner',$params);
            $query = $this->db->get();
//            echo $this->db->last_query();exit;
            return $query->result();
        }

        public function revenues($params){
            $this->db->select_sum('real_fare');
            $this->db->select_sum('net_fare');
            $this->db->select_sum('segments');
            
            $this->db->from($this->table_name);
            $this->db->where('owner',$params);
            $query = $this->db->get();
//                echo $this->db->last_query();exit;
            return $query->result();
        }


        public function export($beginTime,$endTime,$customerID,$userid){
            
                $this->db->select("tbl.id,tbl.voucher_id,tbl.customerID,tbl.booking_place_code, tbl.airline, tbl.booking_types, tbl.booking,tbl.booking_customer_name,tbl.booking_child,tbl.segments,tbl.payment_air, tbl.lastupdated, tbl.createdTime, tbl.net_fare, tbl.real_fare, tbl.note,tbl.payment_method, med.payment_name,usr.firstname AS username,cts.name,cts.phone");
		$this->db->from($this->table_name . ' AS tbl');
                $this->db->join('book_payment_method AS med','med.id=tbl.payment_method','inner');
                $this->db->join('users AS usr','usr.id=tbl.owner','inner');
                $this->db->join('book_contacts AS cts','cts.customerID=tbl.customerID','inner');
                
                if($beginTime){
                    $this->db->where('tbl.createdTime >= '.strtotime($beginTime));
                }
                
                if($endTime){
                    $this->db->where('tbl.createdTime <= '.strtotime($endTime.' 24:00:00'));
                }
                
                if($customerID){
                    $this->db->where('tbl.customerID',$customerID);
                }
                
                if($userid){
                    $this->db->where('tbl.owner',$userid);
                }
//                $this->db->order_by('tbl.createdTime','DESC');
                $query = $this->db->get();
//                echo $this->db->last_query();exit;
                return $query->result();
        }
        
        public function selectAll($where=NULL,$page=NULL){
            $this->db->select("tbl.id,tbl.payment_method,tbl.customerID,tbl.booking_place_code,tbl.booking,tbl.booking_customer_name,tbl.booking_child,tbl.createdTime,tbl.dkve,tbl.dkhanhly,tbl.condition_print,tbl.net_fare,tbl.sale_fare,tbl.real_fare, tbl.airline, tbl.payment_air, tbl.lastupdated, med.payment_name,usr.username,agent.pcc,cts.name");
            $this->db->from($this->table_name . ' AS tbl');
            $this->db->join('book_payment_method AS med','med.id=tbl.payment_method','inner');
            $this->db->join('users AS usr','usr.id=tbl.owner','inner');
            $this->db->join('book_agent_code AS agent','agent.id=tbl.agent_code','inner');
            $this->db->join('book_contacts AS cts','cts.customerID=tbl.customerID','inner');
            $this->db->order_by('tbl.lastupdated','DESC');
            if(isset($where) && $where){
                $this->db->where('tbl.booking_id',$where);
            }
            if(isset($page)){
                $this->db->limit(5,$page*5);
            }
            
            $query = $this->db->get();
//            echo $this->db->last_query();exit;
            return $query->result();
        }
        
        public function insertBankInfo($params){
           $this->bookhistory_model->create($params);
           $result = $this->db->affected_rows();
           if(!$result){
               die("Insert db ".$this->table_name.' fail!');
           }
        }
        
        public function getAir($params){
            $this->load->model('bookairlines_model');
             $result = $this->bookairlines_model->find_by(array('code'=>$params));
             return isset($result[0]->name)?$result[0]->name:'';
        }
        
        public function getAirport($params){
            $this->load->model('bookairport_model');
             $result = $this->bookairport_model->find_by(array('code'=>$params));
             
             if(empty($result)){
                $content               = json_decode(file_get_contents(PRE_API_AIRPORT.$params.'?isDestination=false&ccy=VND'));
                
                $info               = new stdClass();
                $info->code         = $params;
                $info->city         = (isset($content[0]->CityName))?$content[0]->CityName:$content[0]->CountryName;
                $info->cityEn       = (isset($content[0]->CityNameEn))?$content[0]->CityNameEn:$content[0]->CountryName;
                $info->country      = $content[0]->CountryName;
                $info->countryEn    = $content[0]->CountryName;

                 $this->bookairport_model->create($info);
                 $city = $info->cityEn;
                 unset($content);unset($info);
             } else {
                 $city = $result[0]->city;
             }
             return (isset($city))?$city:'';
        }

        public function init_data($right){
		return array(
                                array(
						'name' => 'id',
						'label' => $this->lang->line('number'),
						'width' => '1%',
						'sort'  => 'DESC',
						'searchoptions' => FALSE
				),
                                array(
						'name' => 'name',
						'label' => $this->lang->line('name'),
						'width' => '10%',
						'sort'  => FALSE,
						'searchoptions' => FALSE
				),
				array(
						'name' => 'booking_place_code',
						'label' => $this->lang->line('booking_place_code'),
						'width' => '5%',
						'sort'  => FALSE,
						'searchoptions' => FALSE
				),array(
						'name' 	=> 'airline',
						'label' => $this->lang->line('airline'),
						'width' => '2%',
						'sort'  => FALSE,
						'searchoptions' => FALSE
				),
				array(
						'name' 	=> 'payment_method',
						'label' => $this->lang->line('payment_method'),
						'width' => '5%',
						'sort'  => FALSE,
						'searchoptions' => FALSE
				),
                                array(
						'name' 	=> 'net_fare',
						'label' => $this->lang->line('net_fare'),
						'width' => '4%',
						'sort'  => FALSE,
						'searchoptions' => FALSE
				),array(
						'name' 	=> 'real_fare',
						'label' => $this->lang->line('real_fare'),
						'width' => '5%',
						'sort'  => FALSE,
						'searchoptions' => FALSE
				),
                                array(
						'name' 	=> 'payment_confirm',
						'label' => $this->lang->line('payment_confirm'),
						'width' => '5%',
						'sort'  => FALSE,
						'searchoptions' => FALSE
				),
                                array(
						'name' 	=> 'owner',
						'label' => $this->lang->line('booker'),
						'width' => '5%',
						'sort'  => FALSE,
						'searchoptions' => FALSE
				),array(
						'name' 	=> 'createdTime',
						'label' => $this->lang->line('createdTime'),
						'width' => '7%',
						'sort'  => FALSE,
						'searchoptions' => FALSE
				),array(
						'name' 	=> 'lastupdated',
						'label' => $this->lang->line('lastupdated'),
						'width' => '7%',
						'sort'  => FALSE,
						'searchoptions' => FALSE
				),array(
						'name' 	=> 'tienve',
						'label' => $this->lang->line('tienve'),
						'width' => '5%',
						'sort'  => FALSE,
						'searchoptions' => FALSE
				),array(
						'name' 	=> 'checkerKT',
						'label' => $this->lang->line('checkerKT'),
						'width' => '5%',
						'sort'  => FALSE,
						'searchoptions' => FALSE
				),array(
						'name'  => 'button',
						'width' => '4%',
						'sort'  => FALSE,
						'label'  => FALSE,
						'searchoptions' => FALSE
				)
		);
	}
	
	public function json_data($controller, $right){
                if($this->session->userdata('bookhistory_time')){
                    $time = json_decode($this->session->userdata('bookhistory_time'));
                }
                
                if($this->session->userdata('bookhistory_customerID')){
                    $customerID = json_decode($this->session->userdata('bookhistory_customerID'));
                }
                
                if($this->session->userdata('bookhistory_booking_place_code')){
                    $booking_place_code = json_decode($this->session->userdata('bookhistory_booking_place_code'));
                }
                
                if($this->session->userdata('bookhistory_userid')){
                    $userid = json_decode($this->session->userdata('bookhistory_userid'));
                }
                
                if($this->session->userdata('bookhistory_payment_method')){
                    $payment_method = json_decode($this->session->userdata('bookhistory_payment_method'));
                }
                
		$this->datatables
		->select("tbl.id,tbl.voucher_id,tbl.booking_id,tbl.customerID,tbl.booking,tbl.booking_customer_name,tbl.booking_child,tbl.booking_place_code, tbl.payment_method, tbl.airline, tbl.payment_air, tbl.lastupdated, tbl.createdTime, tbl.net_fare, tbl.real_fare, tbl.segments,tbl.checker AS duyetbaocao, med.payment_name,usr.username,cts.name,bv.real_fare AS ct_real_fare,bv.ticketworkers")
		->from($this->table_name . ' AS tbl')
                ->join('book_payment_method AS med','med.id=tbl.payment_method','inner')
                ->join('users AS usr','usr.id=tbl.owner','inner')
                ->join('book_contacts AS cts','cts.customerID=tbl.customerID','inner')
                ->join('book_voucher AS bv','bv.id=tbl.voucher_id','LEFT');
	
                if(isset($time) && $time->beginTime != ''){
                    $this->datatables->where('tbl.createdTime >= "'.$time->beginTime.'"');
                }
                
                if(isset($time) && $time->endTime != ''){
                    $this->datatables->where('tbl.createdTime <= "'.$time->endTime.'"');
                }
                
                if(isset($customerID) && $customerID->customerID != ''){
                    $this->datatables->where('tbl.customerID',$customerID->customerID);
                }
                
                if(isset($booking_place_code) && $booking_place_code->booking_place_code != ''){
                    $this->datatables->where('tbl.booking_place_code',$booking_place_code->booking_place_code);
                }
                
                if(isset($userid) && $userid->userid != ''){
                    $this->datatables->where('tbl.owner',$userid->userid);
                }
                
                if(isset($payment_method) && $payment_method->payment_method != ''){
                    $this->datatables->where('tbl.payment_method',$payment_method->payment_method);
                }
                
                if(!in_array($this->session->userdata['group_id'],array(1,76,79))){
                    $this->datatables->where('tbl.owner = '.$this->session->userdata['user_id']);
                }
                
		$this->datatables->set_produce_output(false);
		$ouput = $datatables = $this->datatables->generate();
		unset($ouput['aaData']);
                $this->session->unset_userdata('bookhistory_time');
                $this->session->unset_userdata('bookhistory_customerID');
                $this->session->unset_userdata('bookhistory_booking_place_code');
                $this->session->unset_userdata('bookhistory_userid');
                $this->session->unset_userdata('bookhistory_payment_method');
                
		$ouput['aaData'] = array();
                $count = 1;
                $this->load->model('voucher_model');
		foreach($datatables['aaData'] as $item){
                    if($item['ct_real_fare'] > 0){
//                        $real_fare = '<a href="/auth/bookhistory/voucher?id='.$item['voucher_id'].'" class="fancy-sl">Xem</a>';
                        $real_fare = $this->bookinglib->my_number_format($item['ct_real_fare'], 2, ',', ',');
                    } else {
                        $real_fare = $this->bookinglib->my_number_format($item['real_fare'], 2, ',', ',');
                    }
                    
                    if($item['ticketworkers']){
                        $paxname    = explode("||",$item['booking_customer_name']);
                        if($item['booking_child']){
                            $child      = explode(',',$item['booking_child']);
                            foreach($child as $keys => $vals){
                                $paxname[] = trim($vals);
                            }
                        }
                        
                        $ticketworkers      =   $this->voucher_model->find_by(array('id'=>$item['voucher_id']),'ticketworkers');
                        if($ticketworkers[0]->ticketworkers){
                            $item['segments']       = count($paxname) * count(json_decode($item['booking']));
                        }
                    }
			$ouput['aaData'][] = array(
					$count++,
                                        $item['name'],
					$item['booking_place_code'],
					$item['airline'],
                                        $item['payment_name'],
                                        $this->bookinglib->my_number_format($item['net_fare'], 2, ',', ','),
                                        $real_fare,
                                        ($item['payment_air'] == 1)?'OK':'',
                                        $item['username'],
                                        date("d-m-Y H:i:s",$item['createdTime']),
                                        date("d-m-Y H:i:s",$item['lastupdated']),
                                        $this->bookinglib->my_number_format($item['segments']*3000, 2, ',', ','),
                                        ($item['duyetbaocao'] == NULL)?"":$this->lang->line('daduyet'),
					$this->add_button_history($controller, $right, $item['booking_id']),
			);
                        unset($real_fare);
		}
                
		return json_encode($ouput);
	}
        
        public function udpate_confirm($params){
            $sql    = "UPDATE {$this->table_name} SET payment_confirm = 1,real_fare = '".$params['amount']."' WHERE booking_id = '".$params['booking_id']."'";
            $this->db->query($sql);
            return $this->db->affected_rows();
        }
        
        public function _getListPaymentMethod(){
            $payment_method = $this->getListPaymentMethod();
            unset($payment_method[4]);
            return $payment_method;
        }
}